<script>
import axios, {Axios} from "axios";

export default {
  name:'comments',
  created() {
    this.imgSize=[]
    this.selectCommentByCondition()
  },


  methods: {
    //多选
    handleSelectionChange(val) {
      console.log(val)
      this.commentIds=[]
      for (let i = 0; i < val.length; i++) {
        this.commentIds.push(val[i].id)
      }
      console.log(this.commentIds)
    },
    //批量删除
    deleteByIdsComment(done) {
      if (this.commentIds.length == 0) {
        this.$message({
          message: '请先选择权限',
          type: 'warning'
        });
        return

      }
      this.$confirm('是否批量删除？')
          .then(_ => {
            this.$http.delete("comment/delete/"+this.commentIds+" ").then((resp) => {
              if (resp.data.code == 200) {
                this.$message({
                  showClose: true,
                  message: '恭喜你，删除成功',
                  type: 'success'
                });
                this.selectCommentByCondition()
              }
              this.commentIds = []
              done();
            }).catch(error=>{

            })

          })

          .catch(_ => {
          });
    },
    //普通删除
    deleteComment(row){
      this.$http.delete("comment/delete/"+row.id+" ").then(resp=>{
        if (resp.data.code == 200) {
          this.$message({
            showClose: true,
            message: '恭喜你，删除成功',
            type: 'success'
          });
          this.selectCommentByCondition()
        }
      }).catch(error=>{

      })
    },

    selectCommentByCondition() {
      this.$http.post("comment/select?current=" + this.currentPage + "&size=" + this.pageSize + "", this.comment).then((resp) => {
        this.tableData = resp.data.data.list;
        console.log(this.tableData)
        this.total = resp.data.data.total;
      }).catch(error=>{

      })
    },

    //自定义图片上传方法
    uploadFile(param){
     this.fileData = param

    },
    //上传图片成功返回
    handleSuccess(response){
      console.log(response.data)
      this.comment.img = response.data;
    },
    dealImgChange(file, fileList){
      const isJPG =
          file.raw.type === "image/jpeg" || file.raw.type === "image/png"
      const isLt2M = file.raw.size / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 < 10

      if (!isLt2M) {
        this.$message.warning("上传图片大小不能超过 10M!")
        this.fileList=[]
        return
      } else if (!isJPG) {
        this.$message.warning("上传图片格式只能是jpg或png")
        this.fileList=[]
        return
      }
      this.noneBtnImg = fileList.length >= this.limitCountImg;
      this.file = file
      console.log(file)
    },
    //图片方法
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.noneBtnImg = fileList.length >= this.limitCountImg;
      this.file = []
    },
    handlePictureCardPreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
    //添加或修改方法
    async addOrUpdateComments(){
      console.log(this.file)
      if (this.file.length<=0){
        this.$message({
          showClose: true,
          message: '图片不能为空',
          type: 'warning'
        });
        return
      }
      if (this.comment.name == "" || this.comment.comment == ""){
        this.$message({
          showClose: true,
          message: '对象数据不能为空',
          type: 'warning'
        });
        return
      }
      console.log(this.file)
      var FormDatas = new FormData()
      FormDatas.append('file',this.fileData.file);
      console.log(FormDatas.get("file"))

      //上传图片

        const  instance = axios.create({
          withCredentials: true,
          "token":window.localStorage.getItem("token")
        });
       await instance.post("api/file-load/upload",FormDatas).then(res=>{
          this.comment.img = res.data.data
        }).catch(error=>{

        })


      //修改
      if (this.comment.createTime != ""){
        this.$http.put("comment/update",this.comment).then(resp=>{
          if (resp.data.code == 200){
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            });
            this.dialogVisible = false
            this.fileData={}
            this.comment={}
            this.fileList = []
            this.selectCommentByCondition()
          }

        }).catch(error=>{

        })
      }else {
        //添加


          this.$http.post("comment/save",this.comment).then(resp=>{
            if (resp.data.code == 200){
              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              });
              this.dialogVisible = false
              this.fileData={}
              this.fileList = []
              this.selectCommentByCondition()
            }

          }).catch(error=>{})

        }






    },
    //添加弹出框
    addComments(){
      this.dialogVisible=true;
    },
    //关闭弹窗方法
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.noneBtnImg=false
            this.fileData={}
            this.comment={}
            this.dialogImageUrl=""
            this.fileList=[]

          })
          .catch(_ => {});
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.selectCommentByCondition()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.selectCommentByCondition()

    },

    //编辑表单
    handleClick(row) {

      this.comment = row
      this.dialogVisible=true;
      this.dialogImageUrl = "api/file-load/image-download?name="+row.img+" "
      console.log(this.dialogImageUrl)
      this.fileList.push({
        'url': this.dialogImageUrl
      })
      this.noneBtnImg=true
      this.file=row

      console.log(this.file)
    }
  },
  data() {
    return {
      options: [
        {
          value: "",
          label: '无'
        },
        {
          value: "启用",
          label: '启用'
        }, {
          value: "禁用",
          label: '禁用'
        }],
      commentIds:[],
      fileList:[],
      pageSize:5,
      total:10,
      headers: { "Content-Type": "multipart/form-data" },
      fileData: {},
      imageUrl:"",
      file:[],
      //限制图片
      showBtnDealImg:true,
      noneBtnImg:false,
      limitCountImg:1,
      isShowImg:true,
      //图片
      dialogImageUrl: '',
      dialogImageVisible: false,

      comment:{
        id:"",
        name:"",
        comment:"",
        img:"",
        status:"",
        createTime:""
      },
      //弹窗
      dialogVisible: false,
      //分页
      currentPage: 1,
      //查询输入框
      input: '',
      //table表单
      tableData: [{
        id:"",
        name: "",
        email:"",
        comment:"",
        img:"",
        status:""
      }]
    }
  }
}
</script>

<template>
  <div>
    <h1 style="margin-left: 2%;top: 14px;position: relative">客户评论管理</h1>
    <div style="position: relative;margin-left:2%">
    <el-input
        placeholder="请输入客户评论id"
        v-model="comment.id"
        clearable
        class="select"

        style="width: 180px"
    >
    </el-input>

    <el-input
        placeholder="请输入权限名称名称"
        v-model="comment.name"
        style="width: 200px;margin-left: 2px"
        clearable>
    </el-input>

    <el-select v-model="comment.status" placeholder="请选择"
               style="margin-left: 2px;width: 100px">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          style="width: 100px">
      </el-option>
    </el-select>

    <el-button type="primary" icon="el-icon-search" style="margin-left: 2px" @click="selectCommentByCondition">搜索</el-button>

    <el-button type="danger" round style="position: relative;float: right;margin-right: 20px" @click="deleteByIdsComment">批量删除</el-button>
    <el-button type="primary" round style="position: relative;float: right;margin-right: 20px" @click="addComments">新增客户评论</el-button>

</div>
    <el-table
        :data="tableData"
        border
        ref="multipleTable"
        style="width: 100%;margin-top: 1%;margin-left: 1%;border-radius: 2px"
        @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          fixed
          prop="id"
          label="客户评论id"
          width="200">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"
          width="150">
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          width="150">
      </el-table-column>
      <el-table-column
          prop="comment"
          label="评论"
          width="150">
      </el-table-column>
      <el-table-column
          prop="img"
          label="图片"
          width="170">
        <template   slot-scope="scope" >
          <el-image :src="`api/file-load/image-download?name=${scope.row.img}`" style="width: 50px; height: 50px"/>
        </template>
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          width="150">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteComment(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"

    >
    </el-pagination>

<!--添加form表单-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">

      <el-form ref="form" :model="comment" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="comment.name"></el-input>
        </el-form-item>
        <el-form-item label="评论">
          <el-input v-model="comment.comment"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-tooltip :content="'当前状态: ' + comment.status" placement="top">
          <el-switch
              v-model="comment.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="启用"
              inactive-value="禁用"
          ></el-switch>
          </el-tooltip>
        </el-form-item>
<!--        :auto-upload="false"-->
<!--        api/file-load/upload-->
        <el-form-item label="图片上传">
        <el-upload
            ref="upload"
            action=""
            :headers="headers"
            :http-request="uploadFile"
            name="file"
            :file-list="fileList"
            :on-success="handleSuccess"
            :limit="limitCountImg"
            :class="{'hide': noneBtnImg}"
            :on-change="dealImgChange"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogImageVisible" v-if="dialogImageUrl != null ">
          <el-image width="100%" :src=this.dialogImageUrl alt="" />
        </el-dialog>
        </el-form-item>




        <el-form-item>
          <el-button type="primary" @click="addOrUpdateComments">立即创建</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>


    </el-dialog>



  </div>

</template>

<style scoped>
.select{
  width: 200px;
}
.el-pagination{
  text-align: center;
}

::v-deep.hide .el-upload--picture-card {
  display: none;
}


</style>